package keygen.client;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.sun.crypto.provider.SunJCE;

/**
 * 
 * @Description: 验证类 通过用户输入序列号进行解密验证
 * @Author: zhangzuoqiang
 * @Date: Sep 20, 2011
 */
public class DesKeyVilidate {

	public DesKeyVilidate() {

	}

	public static String DESdecrypt(String keyString)
			throws BadPaddingException {
		// 添加新安全算法 , 如果用 JCE 就要把它添加进去
		Security.addProvider(new SunJCE());
		String Algorithm = "DES"; // 定义 加密算法 , 可用 DES,DESede,Blowfish
		String DecText = "";
		try {
			// 解密
			SecretKeyFactory keyFactory = SecretKeyFactory
					.getInstance(Algorithm);
			byte[] keyData = { 1, 9, 8, 2, 0, 8, 2, 1 };
			DESKeySpec keySpec = new DESKeySpec(keyData);
			Key key = keyFactory.generateSecret(keySpec);
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.DECRYPT_MODE, key);
			byte[] clearByte = c1.doFinal(hex2byte(keyString.trim()));
			System.out.println("解密后的二进串 :" + byte2hex(clearByte));
			System.out.println("解密后的信息 :" + (new String(clearByte)));
			DecText = (new String(clearByte));
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (Exception e3) {
			e3.printStackTrace();
		}
		return DecText;
	}

	public static boolean validate(String keyString) {
		// MachineCode mc = new MachineCode();
		String mac = SystemMessageUtil.getLocalMac().get(1);
		try {
			if (mac.equals(DESdecrypt(keyString))) {
				return true;
			}
		} catch (BadPaddingException e) {
			return false;
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	// 字节码转换成16进制字符串
	private static String byte2hex(byte bytes[]) {
		StringBuffer retString = new StringBuffer();
		for (int i = 0; i < bytes.length; ++i) {
			retString.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF))
					.substring(1).toUpperCase());
		}
		return retString.toString();
	}

	// 将16进制字符串转换成字节码
	private static byte[] hex2byte(String hex) {
		byte[] bts = new byte[hex.length() / 2];
		for (int i = 0; i < bts.length; i++) {
			bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2),
					16);
		}
		return bts;
	}
}
